package com.sfx.算法专题.链表.删除链表;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-08-01
 * Time: 23:19
 */
public class Code_2_removeElements {
    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    static class Solution {
        public ListNode removeElements(ListNode head, int val) {
            //删除节点
            ListNode dummy = new ListNode(-1);
            dummy.next = head;
            ListNode prev = dummy;
            ListNode cur = head;
            while (cur != null) {
                if (cur.val == val) {
                    prev.next = cur.next;
                    cur = prev.next;
                } else {
                    prev = cur;
                    cur = cur.next;
                }
            }
            return dummy.next;
        }
    }
    static class Solution2 {
        public Code_3_removeNthFromEnd.ListNode removeElements(Code_3_removeNthFromEnd.ListNode head, int val) {
            if(head == null) return head;
            while(head!= null && head.val == val) {
                head = head.next;
            }
            Code_3_removeNthFromEnd.ListNode cur = head;
            Code_3_removeNthFromEnd.ListNode prev = head;
            while(cur != null) {
                if(cur.val == val) {
                    prev.next = cur.next;
                    cur = prev.next;
                }else {
                    prev = cur;
                    cur = cur.next;
                }
            }
            return head;
        }
    }
}